package com.xmcc.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Preconditions;
import com.xmcc.common.ResultJson;
import com.xmcc.dao.SysUserMapper;
import com.xmcc.dto.SysUserDto;
import com.xmcc.exception.ParamException;
import com.xmcc.pojo.SysLogWithBLOBs;
import com.xmcc.pojo.SysUser;
import com.xmcc.service.SysUserService;
import com.xmcc.utill.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    //添加用户：
    @Override
    public void insert(SysUserDto sysUserDto) {
        //校验
        BeanValidator.check(sysUserDto);
        //判断邮箱是否可用
        checkMail(sysUserDto.getMail(),null);
        //判断电话是否可用
        checkTelephone(sysUserDto.getTelephone(),null);

        //组装sysuser  todo:邮箱电话要加密
        SysUser sysUser = SysUser.builder().mail(sysUserDto.getMail()).telephone(sysUserDto.getTelephone()).deptId(sysUserDto.getDeptId()).remark(sysUserDto.getRemark())
                .status(sysUserDto.getStatus()).username(sysUserDto.getUsername()).build();
        //设置密码 加密
        String password = MD5Utils.calc(PasswordUtil.getPassword());
        sysUser.setPassword(password);

        //操作人 TODO:得从session与request拿
        sysUser.setOperator("驱魔人");
        sysUser.setOperateTime(new Date());
        sysUser.setOperateIp("127.0.0.1");

        sysUserMapper.insertSelective(sysUser);
    }
    // 修改用户数据：
    @Override
    public void update(SysUserDto sysUserDto) {
        //校验
        BeanValidator.check(sysUserDto);
        //判断邮箱与电话是否可用
        checkMail(sysUserDto.getMail(),sysUserDto.getId());
        checkTelephone(sysUserDto.getTelephone(),sysUserDto.getDeptId());

        //组装sysuser  todo:邮箱电话要加密
        SysUser sysUser = SysUser.builder().id(sysUserDto.getId()).mail(sysUserDto.getMail()).telephone(sysUserDto.getTelephone()).deptId(sysUserDto.getDeptId()).remark(sysUserDto.getRemark())
                .status(sysUserDto.getStatus()).username(sysUserDto.getUsername()).build();

        //操作人 TODO:得从session与request拿
        sysUser.setOperator("驱魔人");
        sysUser.setOperateTime(new Date());
        sysUser.setOperateIp("127.0.0.1");

        sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }

    private void checkMail(String mail,Integer id){
       if(sysUserMapper.checkMail(mail,id)>0){
           throw  new ParamException("该邮箱已经注册");
       }
    }
    private void checkTelephone(String telephone,Integer id){
        if (sysUserMapper.checkTelephone(telephone,id)>0){
            throw  new ParamException("该手机号码已经注册");
        }
    }

    //修改密码：
    @Override
    public void updatePassword(Integer id,String oldPassword,String newPassword) {
        checkdPassword(id,oldPassword);
        if(StringUtils.isBlank(newPassword)){
            throw  new ParamException("请输入新密码");
        }
        newPassword = MD5Utils.calc(newPassword);
        sysUserMapper.updatePassword(id,newPassword);
    }
    // 判断原密码是否正确：
    private void checkdPassword(Integer id,String oldPassword){
        oldPassword = MD5Utils.calc(oldPassword);
        if(sysUserMapper.checkOldPassword(id,oldPassword)<=0){
            throw  new ParamException("原密码输入有误");
        }
    }

    @Override
    public ResultJson login(String keyWord, String password) {
        if (StringUtils.isBlank(keyWord) || StringUtils.isBlank(password)){
            throw new ParamException("请按照格式输入用户名密码！！");
        }
        String passwordMD5 = MD5Utils.calc(password);
        SysUser sysUser = sysUserMapper.login(keyWord);
        String message="";
        if (sysUser==null){
            message="用户名输入有误！";
        }else if (!sysUser.getPassword().equals(passwordMD5)){
            message="密码输入有误！";
        }else if (sysUser.getStatus()!=1){
            if (sysUser.getStatus()==0){
                message="该用户已被冻结！";
            }else {
                message = "该用户已离职!";
            }
        }else {
            return ResultJson.success(sysUser);
        }
        return ResultJson.fail(message);
    }


    @Override
    public List<SysUser> queryAll() {
        return sysUserMapper.queryAll();
    }

    @Override
    public List<SysUser> queryByDeptId(Integer deptId) {
        return sysUserMapper.queryByDeptId(deptId);
    }

    @Override
    public void recover(SysLogWithBLOBs sysLogWithBLOBs) {
        //简便方法
        Preconditions.checkNotNull(sysLogWithBLOBs,"带还原的记录不存在");
        //前面为""或者null就是增加
        String newValue = sysLogWithBLOBs.getNewValue();
        String oldValue = sysLogWithBLOBs.getOldValue();
        if(StringUtils.isBlank(newValue)){//删除操作 oldValue插入
            sysUserMapper.insertSelective(JsonUtil.string2object(oldValue, new TypeReference<SysUser>() {
                @Override
                public int compareTo(TypeReference<SysUser> o) {
                    return super.compareTo(o);
                }
            }));
        }else if(StringUtils.isBlank(oldValue)){//新增  执行删除操作
            sysUserMapper.deleteByPrimaryKey(JsonUtil.string2object(newValue, new TypeReference<SysUser>() {
                @Override
                public int compareTo(TypeReference<SysUser> o) {
                    return super.compareTo(o);
                }
            }).getId());
        }else{
            sysUserMapper.updateByPrimaryKey(JsonUtil.string2object(oldValue, new TypeReference<SysUser>() {
                @Override
                public int compareTo(TypeReference<SysUser> o) {
                    return super.compareTo(o);
                }
            }));
        }


    }
}
